import { reqDepartmentData, reqDeleteDepartmentItem } from '@/api/departments'
export default {
  state: {
    data: {}
  },
  mutations: {
    getData(state, val) {
      state.data = val
    }
  },
  actions: {
    async  getDepartmentData({ commit }) {
      try {
        const { data } = await reqDepartmentData()
        commit('getData', data)
      } catch (error) {
        return Promise.reject(error)
      }
    },
    async deletePartmentItem(context, id) {
      try {
        await reqDeleteDepartmentItem(id)
        await context.dispatch('getDepartmentData')
      } catch (error) {
        return Promise.reject(error)
      }
    }
  },
  getters: {
    depts: (state) => {
      try {
        const data = JSON.parse(JSON.stringify(state.data.depts))
        data.forEach((item) => {
          item.children = data.filter(el => el.pid === item.id)
        })
        const res = data.filter(item => item.pid === '' || item.pid === '-1')
        return res
      } catch (error) {
        return []
      }
    },
    companyName: (state) => state.data.companyName
  },
  namespaced: true
}
